package utils

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"time"
)

var Logger *zap.Logger

func InitLogger() error {
	dir := "./log/"
	logName := dir + time.Now().Format("200601") + ".log"

	if _, err := os.Stat(dir); err != nil {
		if !os.IsExist(err) {
			err := os.MkdirAll(dir, os.ModePerm)
			if err != nil {
				return err
			}
		}
	}

	file, err := os.OpenFile(logName, os.O_APPEND|os.O_RDWR|os.O_CREATE, os.ModePerm)
	if err != nil {
		return err
	}

	writeSyncer := zapcore.AddSync(file)
	encoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())
	fileCore := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(writeSyncer, zapcore.AddSync(os.Stdout)), zapcore.DebugLevel)

	Logger = zap.New(fileCore, zap.AddCaller())

	return nil
}

// MD5 hash加密
func MD5(v string) string {
	d := []byte(v)
	m := md5.New()
	m.Write(d)
	return hex.EncodeToString(m.Sum(nil))
}

// RmString 移除不可见字符（\u200b）
func RmString(str string, specialStr map[int]struct{}) (newString string) {
	buf := new(bytes.Buffer)

	for _, v := range []rune(str) {
		if _, ok := specialStr[int(v)]; ok {
			continue
		}
		buf.WriteRune(v)
	}

	newString = buf.String()

	return
}
